package yz.cp.back.auth.sign;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

@Slf4j
public class EncodeUtils {
    @SneakyThrows
    static String sign(String appSecret,Request request) {
        StringBuilder sb = new StringBuilder();
        sb.append(appSecret).append("&");
        Map<String,String> map=request.getMap();
        Set<String> keySet=map.keySet();
        TreeSet<String> sortSet=new TreeSet<String>();
        sortSet.addAll(keySet);
        Iterator<String> it=sortSet.iterator();
        while(it.hasNext())
        {
            String key=it.next();
            if(key.equalsIgnoreCase("sign")){
                continue;
            }
            String value= URLEncoder.encode(map.get(key),"utf-8");
            sb.append(key).append("=").append(value).append("&");
        }
        sb.append(appSecret);
        log.info("sb:{}",sb.toString());
        if(request.getSignType().equalsIgnoreCase("md5")){
           String sign= DigestUtils.md5Hex(sb.toString());
           return sign;
        }else {
            return  null;
        }

    }
}
